package com.qf.qfleadnewscommons.minio;

import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class MinioOperator {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProperties properties;

//    @Autowired
//    private HttpServletRequest request;

    public String uploadHtml(InputStream is){
        String mimeType = "text/html";

        String filename = buildFileName("xxx.html");

        //构建上传参数
        try {
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(properties.getBucket())
                    .contentType(mimeType)
                    //上传到minio后保存的图片地址
                    .object(filename)
                    .stream(is, is.available(), -1)
                    .build();

            minioClient.putObject(args);
        }catch (Exception e){
            e.printStackTrace();

            return null;
        }

        //上传成功后返回访问图片的地址
        String url = properties.getEndpoint() + "/" + properties.getBucket() + "/" + filename;

        return url;
    }


    public String upload(InputStream is,String originFileName,HttpServletRequest request){

        //根据原始文件名获取文件的类型
        ServletContext sc = request.getServletContext();
        String mimeType = sc.getMimeType(originFileName);

        String filename = buildFileName(originFileName);

        //构建上传参数
        try {
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(properties.getBucket())
                    .contentType(mimeType)
                    //上传到minio后保存的图片地址
                    .object(filename)
                    .stream(is, is.available(), -1)
                    .build();

            minioClient.putObject(args);
        }catch (Exception e){
            e.printStackTrace();

            return null;
        }

        //上传成功后返回访问图片的地址
        String url = properties.getEndpoint() + "/" + properties.getBucket() + "/" + filename;

        return url;
    }

    /**
     * 根据url下载图片
     * @param pathUrl : http://localhost:9005/leadnews/2023/04/11/57104e33-1f10-4356-b8db-43934ff2a2d6.jpg
     *                  leadnews/2023/04/11/57104e33-1f10-4356-b8db-43934ff2a2d6.jpg
     * @return
     */
    public byte[] downLoadFile(String pathUrl)  {
        String key = pathUrl.replace(properties.getEndpoint()+"/","");
        int index = key.indexOf("/");
        String bucket = key.substring(0,index); // leadnews
        String filePath = key.substring(index+1); // 2023/04/11/57104e33-1f10-4356-b8db-43934ff2a2d6.jpg
        InputStream inputStream = null;
        try {
            inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(properties.getBucket()).object(filePath).build());
        } catch (Exception e) {
            e.printStackTrace();
        }

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while (true) {
            try {
                if (!((rc = inputStream.read(buff, 0, 100)) > 0)) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            byteArrayOutputStream.write(buff, 0, rc);
        }
        return byteArrayOutputStream.toByteArray();
    }

    /**
     * 根据原始文件名构建一个目录分离 + 唯一文件名
     * @param originFileName
     * @return
     */
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    private String buildFileName(String originFileName) {
        //originFileName -->  abc.jpg
        //originFileName.lastIndexOf(".") -->  3
        //originFileName.substring(3)  --> .jpg
        String suffix = originFileName.substring(originFileName.lastIndexOf("."));

        //2023/06/25
        String dir = sdf.format(new Date());

        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;


        return dir + "/" + fileName;
    }

}
